import requests
import json
from crudtool import GenericCrudTool
import time
from fake_useragent import UserAgent

# 创建UserAgent对象
ua = UserAgent()



tool=GenericCrudTool(host="127.0.0.1",user="root",password="root",db="coin_account")
proxies = {
    'http': 'http://120.26.52.35:80',
    'http': 'http://183.214.203.219:8060',
     'http': 'http://222.66.202.6:80',
      'http': 'http://39.105.5.126:80',
       'http': 'http://183.236.123.242:8060',
        'http': 'http://111.59.4.88:9002',
         'http': 'http://60.170.204.30:8060',
          'http': 'http://218.75.102.198:8000',
           'http': 'http://60.205.132.71:80',
            # 'http': 'http://221.6.139.190:9002',

}

def access_web( address):
    # 生成随机User-Agent
    headers = {
        'User-Agent': ua.random,
        'Referer': 'https://www.google.com/'  # 可自定义其他头信息
    }
    url=f"http://api.trongrid.io/v1/accounts/{address}"
    try:
        # resp = requests.get(url, proxies=proxies)
        resp = requests.get(url,headers=headers)
    except Exception as e:
        print("Error: {}".format(e))
        return None
    else:
        if resp.status_code ==200:
            return resp.text
        else:
            print('Status code was {}.'.format(resp.status_code))
            return None

def parse_content(content):
    if content is None:
        return 0,""
    else:
        json_data = json.loads(content)
        if len(json_data['data']) >0 :
            return 1,content
    return -1,""

def make_address_page(id):
    print(f"batchid:{id}")
    sql="select * from tb_tag where state=1 and id > %s limit 10 "
    dataItems=tool.execute_query(sql,(id,))
    result=[]
    if len( dataItems) ==0:
        return [],-1
    lastId=0
    for item in dataItems:
        address=item["address"]
        content=access_web(address)
        if content is None:
            print(f"服务出错，无法调用,id:{item['id']}")
            return [],-1
        print(f"content:{content}")
        flag,resContent=parse_content(content)
        if flag==1:
            print(f"合规账号,id:{item['id']}")
        result.append({"id":item["id"],"balance_flag":flag,"state":2,"content":resContent})
        lastId=item["id"]
    return result,lastId

def do_address_work():
    id=0
    result,lastId=make_address_page(id)
    if len(result)>0:
        tool.batch_update("tb_tag",result)
    id=lastId
    while True:
        if id==-1:
            break
        result,lastId=make_address_page(lastId)
        if len(result)>0:
            tool.batch_update("tb_tag",result)
        id=lastId
        print(f"lastId:{lastId}")
        time.sleep(1)

if __name__ == '__main__':
    # address = "TDRMtbs1HNmwnZ3SMRUPtrnqarrMgfSxAn"
    # content = access_web(address=address)
    # flag,rescontent=parse_content(content)
    # print(flag)
    while True:
        try:
            do_address_work()
        except Exception as e:
            pass
        time.sleep(30)
    print("finish")